<?php
/**
 * Common util methods for Upload extension
 */
class UploadUtils {

    private function UploadUtils() {}

    ////////////////////////////////////////////////////////////////////// URL's
    public static function getPath($fileDir) {
        $fullFileDir = dirname(Yii::app()->getRequest()->getScriptFile()).DIRECTORY_SEPARATOR.$fileDir;
        if (!file_exists($fullFileDir)) mkdir($fullFileDir, 0777, true); // Create recursive
        return $fullFileDir;
    }
    public static function getUrl($fileDir) {
        return Yii::app()->request->baseUrl.'/'.$fileDir;
    }


    /////////////////////////////////////////////////////////////////// Database
    public static function findFiles($entity, $EXid=-1) {
        if ($EXid != -1) {
            return File::model()->findAll(array(
                'condition'=>'entity=:entity AND EXid=:EXid',
                'params'=>array(':entity'=>$entity,':EXid'=>$EXid),
                'order'=>'weight ASC',
            ));
        } else {
            return File::model()->findAll(array(
                'condition'=>'entity=:entity',
                'params'=>array(':entity'=>$entity),
                'order'=>'weight ASC',
            ));
        }
    }
    public static function countFiles($entity, $EXid=-1) {
        if ($EXid>0) {
            return File::model()->count('entity=:entity AND EXid=:EXid', array(
                        ':entity'=>$entity,
                        ':EXid'=>$EXid));
        } else {
            return File::model()->count('entity=:entity', array(
                        ':entity'=>$entity));
        }
    }
    public static function deleteFiles($model, $fileDir) {
        $files=File::model()->findAll(array(
            'condition'=>'entity=:entity AND EXid=:EXid',
            'params'=>array(
                ':entity'=>get_class($model),
                ':EXid'=>$model->getPrimaryKey(),
            ),
        ));
        foreach($files as $file) {
            self::deleteFile($file, $fileDir);
        }
    }
    public static function deleteFile($file, $fileDir) {
        unlink(UploadUtils::getPath($fileDir).DIRECTORY_SEPARATOR.$file->filename);
        if (!$file->isNewRecord) $file->delete();
    }


    //////////////////////////////////////////////////////////////////// Session
    public static function clearSessionFiles() {
        unset(Yii::app()->session['temp_files']);
    }
    public static function getSessionFiles() {
        $files = array();
        $sessionFiles = Yii::app()->session['temp_files'];
        if (isset($sessionFiles))
            foreach($sessionFiles as $f) $files[] = File::buildFromArray($f);
        return $files;
    }
    public static function addFileToSession($file) {
        // Store it in session
        $sessionFiles = Yii::app()->session['temp_files'];
        $sid = UploadUtils::generateUniqueSessionId($sessionFiles);
        $file->sid = $sid;
        $sessionFiles[$sid] = $file->toArray();
        Yii::app()->session['temp_files'] = $sessionFiles;        
    }
    public static function getFileFromSession($sid) {
        // Store it in session
        $sessionFiles = Yii::app()->session['temp_files'];
        foreach($sessionFiles as $key=>$file) {
            $file_obj = File::buildFromArray($file);
            if ($file_obj->sid == $sid) {
                unset(Yii::app()->session['temp_files'][$key]);
                return $file_obj;
            }
        }
        return null;
    }
    public static function generateUniqueSessionId($sessionFiles) {
        if (is_array($sessionFiles)) {
            $maxSessionId = 0;
            foreach($sessionFiles as $key=>$file) {
                if ($maxSessionId<$key) $maxSessionId=$key;
            }
            return $maxSessionId+1;
        } else {
            return 1;
        }
    }


    ///////////////////////////////////////////////////////////////// Generation
    /** Creates a unique filename in the directory specified adding a counter suffix */
    public static function createUniquefilename($basename, $directory) {
        $basename = UploadUtils::escapeStrangeChars($basename);
        $dest = $directory.DIRECTORY_SEPARATOR.$basename;

        if (file_exists($dest)) {
            // Destination file already exists, generate an alternative.
            $pos = strrpos($basename, '.');
            if ($pos) {
                $name = substr($basename, 0, $pos);
                $ext = substr($basename, $pos);
            } else {
                $name = $basename;
            }

            $counter = 0;
            do {
                $dest = $directory .'/'. $name .'_'. $counter++ . $ext;
            } while (file_exists($dest));
        }

        return basename($dest);
    }

    /** Escapes the odd chars in a text */
    public static function escapeStrangeChars($text) {
        $text = htmlentities($text, ENT_QUOTES, 'UTF-8');
        $text = strtolower($text);
        $patron = array (
            // Vocales
            '/&agrave;/' => 'a','/&egrave;/' => 'e','/&igrave;/' => 'i','/&ograve;/' => 'o','/&ugrave;/' => 'u',
            '/&aacute;/' => 'a','/&eacute;/' => 'e','/&iacute;/' => 'i','/&oacute;/' => 'o','/&uacute;/' => 'u',
            '/&acirc;/'  => 'a','/&ecirc;/'  => 'e','/&icirc;/'  => 'i','/&ocirc;/'  => 'o','/&ucirc;/'  => 'u',
            '/&atilde;/' => 'a','/&etilde;/' => 'e','/&itilde;/' => 'i','/&otilde;/' => 'o','/&utilde;/' => 'u',
            '/&auml;/'   => 'a','/&euml;/'   => 'e','/&iuml;/'   => 'i','/&ouml;/'   => 'o','/&uuml;/'   => 'u',
            '/&auml;/'   => 'a','/&euml;/'   => 'e','/&iuml;/'   => 'i','/&ouml;/'   => 'o','/&uuml;/'   => 'u',
            // Otras letras y caracteres especiales
            '/&aring;/' => 'a','/&ntilde;/' => 'n',
            // Agregar aqui mas caracteres si es necesario
            '/&amp;/' => 'and','/&lt;/' => 'lt','/&gt;/' => 'gt',

        );
        $text = preg_replace(array_keys($patron),array_values($patron),$text);
        return $text;
    }
    /** Defines if a filemime is an image */
    public static function isImageFileMime($filemime) {
        static $image_mimes = array("image/gif", "image/jpeg", "image/png");
        return in_array($filemime, $image_mimes);
    }
}